<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部组件 -->
      <pageTools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="warning" size="small" @click="eportData">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </pageTools>
      <!-- 表格组件 -->
      <el-table v-loading="loading" border="" :data="list">
        <el-table-column label="序号" sortable="" type="index" width="70" align="center" />
        <el-table-column label="姓名" sortable="" prop="username" align="center" />
        <el-table-column label="头像" align="center">
          <!-- 插槽  -->
          <template v-slot="{ row }">
            <img
              v-imageerror="defaultImg"
              :src="row.staffPhoto"
              alt=""
              style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
              @click="code(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column label="工号" sortable="" prop="workNumber" align="center" />
        <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" align="center" :formatter="formatterEmployment" />
        <el-table-column label="部门" sortable="" prop="departmentName" align="center" />
        <!-- 作用域插槽 + 过滤器 -->
        <el-table-column label="入职时间" sortable="" prop="timeOfEntry" align="center" width="120px">
          <template v-slot="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" sortable="" prop="enableState" align="center">
          <template v-slot="{ row }">
            <el-switch :value="row.enableState === 1" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280" align="center">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" justify="center" style="height:60px" align="middle">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.size"
          :current-page="page.page"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 放置新增员工弹层 -->
    <addEmployee :show-dialog.sync="showDialog" />
    <el-dialog title="二维码" :visible.sync="showCode" width="300px">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 角色权限弹层组件 -->
    <assignRole ref="assignRole" :show-dialog.sync="showAssignRole" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, deleteEmployee } from '@/api/employees'
import employeesEnum from '@/api/constant/employees' // 引入员工的枚举对象
import addEmployee from './components/add-employee'
import { formatDate } from '@/filters'
import qrcode from 'qrcode'
import assignRole from './components/assign-role'
export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      showCode: false,
      defaultImg: require('@/assets/common/head.jpg'),
      list: [], // 员工数据
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false, // 显示遮罩层
      showDialog: false,
      showAssignRole: false, // 显示角色的弹层
      userId: null
    }
  },
  created() {
    // 获取员工信息
    this.getEmployeeList()
  },
  methods: {
    // 点击角色方法
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailBayId(id) // 调用子组件的方法
      this.showAssignRole = true
    },
    // 转化二维码
    code(url) {
      if (url) {
        this.showCode = true
        this.$nextTick(() => {
          // 此时已经可以确认有ref对象
          qrcode.toCanvas(this.$refs.myCanvas, url) // 将地址转化为二维码链接
        })
      } else {
        this.$message.warning('该用户还没有头像')
      }
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('确认删除员工吗？')
        await deleteEmployee(id)
        this.$message.success('删除员工成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 获取员工信息
    async getEmployeeList() {
      this.loading = true // 开启loading
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false // 关闭loading
    },
    // 页码发生改变 newPage 最新的页码
    changePage(newPage) {
      this.page.page = newPage // 赋值最新的页码
      this.getEmployeeList() // 重新拉去数据
    },
    // 格式化聘用形式 row行数据 colunm列属性 cellValue单元格的值
    formatterEmployment(row, column, cellValue, index) {
      const obj = employeesEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 点击新增
    addEmployee() {
      this.showDialog = true // 开启弹出层
    },
    // 导出表格
    eportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        // excel引入文件的导出对象
        // 获取所有数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(rows, headers)// 转化数据 返回的data就是导出的结构
        // 导出复杂标头 一个数组是一行标头
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2'] // 合并标头
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头
          data,
          filename: '员工工资', // 文件的名字
          multiHeader,
          merges
        })
      })
    },
    // 将表头数据和数据进行对应 数组套数组
    formatJson(rows, headers) {
      return rows.map(item => {
        // 得到的是中文的表头数组
        return Object.keys(headers).map(key => {
          // 需要判断correctionTime / timeOfEntry 需要序列化
          if (headers[key] === 'correctionTime' || headers[key] === 'timeOfEntry') {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            // 聘用形式
            const obj = employeesEnum.hireType.find(obj => obj.id === item[headers[key]])
            // 找到返回里面的value
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
      // return rows.map(item => Object.keys(headers).map(key => item[headers[key]]))
    }
  }
}
</script>

<style>

</style>
